package com.apes.fn.server.productRequireManage.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.scm.masterdata.enumeration.model.BusinessParam;
import com.apes.scm.masterdata.enumeration.repository.BusinessParamRepository;
import com.apes.fn.mdm.supplierConfiguration.SupplierBusinessScopeService;
import com.apes.fn.server.productRequire.ProductRequire;
import com.apes.fn.server.productRequire.ProductRequireItem;
import com.apes.fn.server.productRequire.ProductRequireItemRepository;
import com.apes.fn.server.productRequire.SupplierPurchaseOrderService;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.PredicateBuilder;
import com.apes.framework.jpa.spec.Specifications;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.rop.converter.DateUtils;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.ReflectUtil;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service("replenishmentManagementNewService")
public class ReplenishmentManagementNewService extends DomainService {

    @Autowired
    private ProductRequireItemRepository productRequireItemRepository;
    @Autowired
    private BusinessParamRepository businessParamRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private RepleAcceptEntranceService repleAcceptEntranceService;
    @Autowired
    private ReplePurSumItemService replePurSumItemService;
    @Autowired
    private ReplePurOrderService ReplePurOrderService;
    @Autowired
    private RepleDumpSumItemService repleDumpSumItemService;
    @Autowired
    private RepleDumpOrderService repleDumpOrderService;

    @Autowired
    private SupplierPurchaseOrderService supplierPurchaseOrderService;



    // 查询需要补货的要货单
    public List<Map> queryRequireItem(SimpleRequest simpleRequest) {
        JSONObject getJO = simpleRequest.getJO();
        Specification condi = this.appendCondi(getJO);
        List<ProductRequireItem> items = productRequireItemRepository.findAll(condi, Sort.by(Sort.Direction.DESC, "id", "productRequire.approveDate"));
        if (items.isEmpty()) throw new RuntimeException("未找到要货相关数据");
        List<Map> requireGaps = this.convertDataType(items);
        if (requireGaps.isEmpty()) throw new RuntimeException("未找到要货相关数据");
        return requireGaps;
    }

    // 数据格式化返回
    private List<Map> convertDataType(List<ProductRequireItem> items) {
        List fields = Arrays.asList("id", "name");
        List convertMaps = new ArrayList();
        AtomicBoolean fckbjFlag = new AtomicBoolean(false);
        Set<String> unValidRequire = new HashSet<>();
        items.forEach(item -> {
            if (item.getQtyRequire() - item.getQtyAssigned() - item.getQtyEnded() - item.getOrderQty() <= 0) return;
            Store store = getBean(StoreRepository.class).findByDept(item.getProductRequire().getLocation().getDepot().getDept());
            if (store.isFckbj()) {
                fckbjFlag.set(true);
                unValidRequire.add(item.getProductRequire().getId());
                return;
            }
            if (StringUtils.hasText(item.getCommodityInquiryOrderId()) && item.getCommodityInquiryOrderId().startsWith("WC")) return;

            Map requireItemMap = new HashMap();
            requireItemMap.put("toBeReplenishedQty", 0); // 待补货数量
            requireItemMap.put("id", item.getId());
            requireItemMap.put("spId", item.getSpId());
            requireItemMap.put("channelType", item.getChannelType());
            requireItemMap.put("offerId", item.getOfferId());
            requireItemMap.put("commodityInquiryOrderId", item.getCommodityInquiryOrderId());
            requireItemMap.put("uniqueValue", item.getUniqueValue());
            requireItemMap.put("product", this.accordFieldValue(item.getProduct(), fields));
            requireItemMap.put("uom", this.accordFieldValue(item.getUom(), fields));
            requireItemMap.put("qtyRequire", item.getQtyRequire());
            requireItemMap.put("qtyAssigned", item.getQtyAssigned());
            requireItemMap.put("qtyEnded", item.getQtyEnded());
            requireItemMap.put("orderQty", item.getOrderQty());
            requireItemMap.put("supplier", this.accordFieldValue(item.getSupplier(), fields));

            requireItemMap.put("site", this.accordFieldValue(item.getSite(), fields));
            requireItemMap.put("purchasingGroup", this.accordFieldValue(item.getPurchasingGroup(), fields));
            requireItemMap.put("classifyId", item.getProduct().getClassify().getId());
            requireItemMap.put("brandId", item.getProduct().getBrand().getId());
            requireItemMap.put("expectedArrivalTime", item.getExpectedArrivalTime());
            if (!ObjectUtils.isEmpty(item.getSourceState())) {
                requireItemMap.put("sourceStateId", item.getSourceState().getId());
                requireItemMap.put("sourceStateCode", item.getSourceState().getCode());
            }
            if (!ObjectUtils.isEmpty(item.getCommodityInquiryOrderId()) && item.getCommodityInquiryOrderId().startsWith("BI")) {
                requireItemMap.put("errorMessage", item.getProductRequire().getInterfacePushFail());
            } else {
                requireItemMap.put("errorMessage", item.getErrorMessage());
            }

            ProductRequire productRequire = item.getProductRequire();
            requireItemMap.put("productRequireId", productRequire.getId());
            requireItemMap.put("source", productRequire.getSource());
            requireItemMap.put("version", productRequire.getVersion());
            requireItemMap.put("sourceBusinessType", productRequire.getSourceBusinessType());
            requireItemMap.put("creatorName", productRequire.get_creator().getParty().getName());
            if (!Objects.isNull(productRequire.getApproveDate())) requireItemMap.put("approveDate", DateUtil.format(productRequire.getApproveDate(), DateUtil.SHOW_DATETIME_FORMAT));
            requireItemMap.put("location", this.accordFieldValue(productRequire.getLocation(), fields));
            requireItemMap.put("locationCompany", this.accordFieldValue(productRequire.getLocation().getCompany(), fields)); // requireLocationCompanyId、requireLocationCompanyName
            requireItemMap.put("platform", this.accordFieldValue(productRequire.getPlatform(), fields));
            requireItemMap.put("customerExpand", this.accordFieldValue(productRequire.getCustomerExpand(), Arrays.asList("id", "carLicense", "vin", "jekunModelCode", "")));
            if (!Objects.isNull(productRequire.getStore())) {
                requireItemMap.put("store", this.accordFieldValue(productRequire.getStore(), Arrays.asList("id", "name", "telephone", "address")));
                requireItemMap.put("wantInvoice", productRequire.getStore().getCompany().getParty().getCorporate().isWantInvoice());
            }
            convertMaps.add(requireItemMap);
        });

        if (convertMaps.isEmpty() && fckbjFlag.get()) throw new RuntimeException("查询条件范围内所有门店已禁用 或 已封库，无法操作, 要货单：" + unValidRequire.toString());
        return convertMaps;
    }


    // 根据实体获取制定字段的值
    private Map accordFieldValue(Object obj, List<String> fieldList){
        Map map = new HashMap();
        if (ObjectUtils.isEmpty(obj)) return null;
        fieldList.forEach(filed -> {
            map.put(filed,  ReflectUtil.getFieldValue(obj, filed));
        });
        return map;
    }


    // 获取查询条件
    private List filterCondi(JSONObject getJO) {
        List allColumn = new ArrayList();
        allColumn.addAll(Arrays.asList("requireId", "usage", "product", "location", "brand", "appRequire", "serveType", "classify", "requireDate", "platform",
                "purchasingGroup", "commodityInquiryOrderId", "dumpChannelType", "autoDumpChanelIds", "commodityInquiryOrderIdPurchase", "purchaseGroupIdIsNotNull", "mainChanelType"));
        List getJOColumn = new ArrayList();
        getJO.keySet().forEach(column -> {
            String value = getJO.getString(column);
            if (StringUtils.hasText(value) && !value.equals("[]"))  getJOColumn.add(column);
        });
        allColumn.retainAll(getJOColumn);
        return allColumn;
    }


    // 拼接查询条件
    private Specification appendCondi(JSONObject getJO) {
        List validColumns = this.filterCondi(getJO);

        PredicateBuilder predicateBuilder = Specifications.and();

        predicateBuilder.in("productRequire.state", Arrays.asList("approve", "repeal"));
        Specification specification = predicateBuilder.build(false);

//        if (!validColumns.contains("commodityInquiryOrderId") && !validColumns.contains("commodityInquiryOrderIdPurchase")) { // 转储订单传commodityInquiryOrderId，自动采购传 commodityInquiryOrderIdPurchase，界面查询无
//            predicateBuilder.eq("commodityInquiryOrderId", null);
//        }

        for (int i = 0, iLen = validColumns.size(); i < iLen; i++) {
            String columnName = String.valueOf(validColumns.get(i));
            String value = getJO.getString(columnName);
            switch (columnName) {
                case "requireId":
                    PredicateBuilder predicateBuilder2 = Specifications.or();
                    predicateBuilder2.eq("productRequire.id", value);
                    predicateBuilder2.eq("productRequire.source", value);
                    specification = specification.and(predicateBuilder2.build(false));
                    break;
                 case "usage":
                     predicateBuilder.eq("productRequire.location.usage.id", this.obtainValue(JSONObject.parseObject(value), "id"));
                     break;
                 case "product":
                     predicateBuilder.eq("product.id", this.obtainValue(JSONObject.parseObject(value), "id"));
                     break;
                 case "location":
                     predicateBuilder.eq("productRequire.location.id", this.obtainValue(JSONObject.parseObject(value), "id"));
                     break;
                 case "brand":
                     predicateBuilder.eq("product.brand.id", this.obtainValue(JSONObject.parseObject(value), "id"));
                     break;
                 case "appRequire":
                     predicateBuilder.in("productRequire.channel.id", Arrays.asList("50", "70", "100"));
                     break;
                case "autoDumpChanelIds": // 自动转储条件
                    PredicateBuilder predicateBuilder3 = Specifications.or();
                    predicateBuilder3.notIn("productRequire.channel.id", getJO.get(columnName));
                    predicateBuilder3.eq("productRequire.channel.id", null);
                    specification = specification.and(predicateBuilder3.build(false));
                    break;
                case "dumpChannelType": // 自动转储条件
                    PredicateBuilder predicateBuilder4 = Specifications.or();
                    predicateBuilder4.notIn("channelType",1, 4);
                    predicateBuilder4.eq("channelType", null);
                    specification = specification.and(predicateBuilder4.build(false));
                    break;
                 case "serveType":
                     predicateBuilder.eq("productRequire.serveType.id", this.obtainValue(JSONObject.parseObject(value), "id"));
                     break;
                 case "classify":
                     predicateBuilder.like("product.classify.id", value + "%");
                     break;
                 case "requireDate":
                     JSONArray dataArray = JSONArray.parseArray(getJO.getString(columnName));
                     predicateBuilder.ge("productRequire.approveDate", DateUtil.parse(dataArray.getString(0), DateUtils.SHOW_DATETIME_FORMAT));
                     predicateBuilder.le("productRequire.approveDate", DateUtil.parse(dataArray.getString(1), DateUtils.SHOW_DATETIME_FORMAT));
                     break;
                 case "platform":
                      predicateBuilder.eq("productRequire.platform.id", this.obtainValue(JSONObject.parseObject(value), "id"));
                      break;
                 case "purchasingGroup":
                     predicateBuilder.eq("purchasingGroup.id", this.obtainValue(JSONObject.parseObject(value), "id"));
                     break;
                case "fnCustomerExpandTemp":
                    predicateBuilder.eq("productRequire.customerExpand.carLicense", this.obtainValue(JSONObject.parseObject(value), "carLicense"));
                    break;
                case "commodityInquiryOrderId": // 自动转储条件
                    PredicateBuilder predicateBuilder5 = Specifications.or();
                    predicateBuilder5.eq("commodityInquiryOrderId", null);
                    predicateBuilder5.ne("channelType", 3);

                    PredicateBuilder predicateBuilder6 = Specifications.and();
//                    predicateBuilder6.notLike("commodityInquiryOrderId", "ST%");
                    predicateBuilder6.notLike("commodityInquiryOrderId", "BI%");
                    predicateBuilder6.notLike("commodityInquiryOrderId", "WC%");
                    predicateBuilder5.predicate(predicateBuilder6.build(false));

                    specification = specification.and(predicateBuilder5.build(false));
                    break;

                case "commodityInquiryOrderIdPurchase": // 自动采购
                    PredicateBuilder predicateBuilder8 = Specifications.or();
                    predicateBuilder8.isNotNull("channelType");
                    predicateBuilder8.isNotNull("commodityInquiryOrderId");
                    specification = specification.and(predicateBuilder8.build(false));

//                    predicateBuilder.notLike("commodityInquiryOrderId", "WC%");
                    break;

                case "purchaseGroupIdIsNotNull": // 自动采购
                    predicateBuilder.isNotNull("purchasingGroup.id");
                    break;
                case "mainChanelType": // 自动采购
                    PredicateBuilder predicateBuilder7 = Specifications.or();
                    predicateBuilder7.ne("productRequire.channel.id", value);
                    predicateBuilder7.eq("productRequire.channel.id", null);
                    specification = specification.and(predicateBuilder7.build(false));
                    break;
            }

        }


        specification = specification.and(predicateBuilder.build(false));
        return specification;
    }

    // 根据类型获取值
    private String obtainValue(Object value, String column) {
        if (value instanceof JSONObject) {
            return ((JSONObject) value).getString(column);
        } else if (value instanceof String) {
            return (String) value;
        }
        return "";
    }



    // 点击采购 - 汇总
    public JSONObject purchaseSum(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONArray requireItems = getJO.getJSONArray("productRequireItems");

        JSONObject requireItemPurSumObj = repleAcceptEntranceService.acceptOrderSum(replePurSumItemService, new JSONObject(MapUtil.mapper("productRequireItems", requireItems)));
        getJO.put("purchaseRequireItems", requireItemPurSumObj.getJSONArray("item"));
        getJO.put("requireItemErrorLog", requireItemPurSumObj.get("requireItemErrorLog"));
        return getJO;
    }

    // 点击转储 - 汇总
    public JSONObject dumpSum(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONArray filterValidRequireItem = getJO.getJSONArray("productRequireItems").stream()
                .filter(requireItem -> {return ((JSONObject) requireItem).getBooleanValue("selectFlag");}).collect(Collectors.toCollection(JSONArray::new));
        if (filterValidRequireItem.isEmpty()) throw new RuntimeException("请检查是否勾选数据！");

        JSONObject data = repleAcceptEntranceService.acceptOrderSum(repleDumpSumItemService, new JSONObject(MapUtil.mapper("item", filterValidRequireItem)));
        getJO.put("allRequireId", data.get("allRequireId"));
        getJO.put("sumProductRequireItems", data.get("sumProductRequireItems"));
        return getJO;
    }

    // 转储 - 生成转储单
    public JSONObject generatorDumpOrder(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONObject fLocationObj = getJO.getJSONObject("location");
        if (Objects.isNull(fLocationObj)) throw new RuntimeException("请选择配货仓库 !");

        JSONArray requireItems = getJO.getJSONArray("sumProductRequireItems");
        JSONArray checkRequireItems = requireItems.stream().filter(item -> ((JSONObject) item).getBooleanValue("checkData") && ((JSONObject) item).getDoubleValue("distributionQty") != 0)
                .collect(Collectors.toCollection(JSONArray::new));
        if (checkRequireItems.isEmpty()) throw new RuntimeException("未获取到有效数据！请检查是否填写转储数量"); // 此报错有用到

        Map responseData =
                repleAcceptEntranceService.acceptOrder(repleDumpOrderService, new JSONObject(MapUtil.mapper("item", checkRequireItems, "location", fLocationObj, "allRequireId", getJO.get("allRequireId"))));

        JSONObject result = this.notReplenishmentCompleted(getJO);
        result.put("sucessNumber", "转储成功! \r\n" + responseData.get("orderId"));
        return result;
    }

    // 转储 - 获取可分配数量
    public JSONObject obtainStock(SimpleRequest request) {
        return repleDumpSumItemService.obtainStock(request.getJO());
    }

    // 采购 - 生成采购订单
    public JSONArray generatorPurOrder(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONArray requireItems = getJO.getJSONArray("purchaseRequireItems");

        // 异常商品处理后再继续
        this.judgeProductState(requireItems);
        JSONArray checkRequireItems = requireItems.stream()
                .filter(item -> {
                    JSONObject itemO = (JSONObject) item;
                    return itemO.getBooleanValue("checkData") && itemO.getDoubleValue("distributionQty") != 0 && itemO.getDoubleValue("P001") != 0 && !StringUtils.isEmpty(itemO.get("contract"));
                }).collect(Collectors.toCollection(JSONArray::new));
        if (checkRequireItems.size() == 0) throw new RuntimeException("请检查是否勾选数据、填写采购数量、价格、合同信息！");

        // 再过滤一遍【价格是否一致】，但是不作为硬提示
        checkRequireItems = requireItems.stream()
                .filter(item -> {
                    JSONObject itemO = (JSONObject) item;
                    return itemO.getBooleanValue("priceConsistent") || !"5".equals(itemO.getString("channelType"));
                }).collect(Collectors.toCollection(JSONArray::new));


        // 写入异常日志
        JSONArray requireItemErrorLog = getJO.getJSONArray("requireItemErrorLog");
        this.writeItemLoggerAndUpdateRequireItem(requireItemErrorLog, checkRequireItems);

        // 分发三方询价要货并创建订单
        JSONArray invaildDataArray = this.issueThirdInquireRequireOrder(checkRequireItems);

        JSONArray requireItemsClone = (JSONArray) requireItems.clone();
        requireItemsClone.removeAll(invaildDataArray);

        // 最后判断勾选的是否全部采购完毕，未采购完毕的返回前端
        return this.judgePurchaseNoReplenished(requireItems);
    }

    // 要货明细异常日志写入
    private void writeItemLoggerAndUpdateRequireItem(JSONArray requireItemErrorLogs, JSONArray checkRequireItems) {
        if (requireItemErrorLogs == null || requireItemErrorLogs.isEmpty()) return;
        for (int i = 0; i < requireItemErrorLogs.size(); i++ ) {
            JSONObject requireItemLogObj = requireItemErrorLogs.getJSONObject(i);
            String requireItemId = requireItemLogObj.getString("id");

            boolean moveFlag = moveLogJudge(checkRequireItems, requireItemId);
            if (moveFlag) {
                requireItemErrorLogs.remove(i);
                i--;
                continue;
            }

            String errorMessage = requireItemLogObj.getString("errorMessage");
            ProductRequireItem requireItem = productRequireItemRepository.findOne(requireItemLogObj.getString("id"));
            requireItem.setErrorMessage(errorMessage);
            productRequireItemRepository.save(requireItem);

            this.appendRequireLogger(requireItem.getProductRequire().getId(), "ProductRequire", "生成供应商订单", 0,
                    errorMessage + ", 商品：" + requireItem.getProduct().getId());
        }
    }

    private boolean moveLogJudge(JSONArray checkRequireItems, String requireItemId) {
        for (int j = 0; j < checkRequireItems.size(); j++ ) {
            JSONObject checkRequireItemObj = checkRequireItems.getJSONObject(j);
            String requireItemIdCheck = checkRequireItemObj.getString("id");
            boolean priceConsistent = checkRequireItemObj.getBooleanValue("priceConsistent"); // 前端可能做更改价格的情况，无价格或价格不合理，可以选择其他渠道的价格，其他渠道的价格不做价格一致判断，默认true
            if (requireItemId.equals(requireItemIdCheck)) {
                return priceConsistent; // 价格一致不做日志异常
            }
        }
        return false;
    }

    private void appendRequireLogger(String businessKey, String businessType, String operate, int operatorId, String remark) {
        invoke("ir.logger.save",
                MapUtil.mapper("businessKey", businessKey, "businessType", businessType, "operator_id", operatorId, "operate", operate,
                        "businessDate", new Date(), "remark", remark));
    }

    /**
     * 创建供应商平台订单
     * @param jsonArray
     * @return
     */
    public JSONArray supplierOeder(JSONArray jsonArray,SimpleRequest request){
        JSONArray array = new JSONArray();
        Map<String,List<Object>> map = jsonArray.stream().collect(Collectors.groupingBy(item -> ((JSONObject)item).getString("productRequireId")));
        map.forEach((k,v)->{
            List<ProductRequireItem> list = new ArrayList<>();
            for (Object o:v) {
                JSONObject jsonObject = (JSONObject)o;
                if(jsonObject.getString("selected")!=null && !jsonObject.getBoolean("selected")) continue;
                ProductRequireItem productRequireItem =  productRequireItemRepository.findOne(jsonObject.getString("id"));
                if(productRequireItem.getChannelType()!=null && (productRequireItem.getChannelType()==1 || productRequireItem.getChannelType()==2)){
                    list.add(productRequireItem);
                    array.add(jsonObject);

                }
            }
            if(list.size()>0) {
                if(request.getSession()==null){ throw new RuntimeException("用户信息丢失，请刷新页面！"); }
                boolean is = supplierPurchaseOrderService.CreateSupplierOrder(list,request);
                if (!is) {
                    throw new RuntimeException("生成采购订单失败！");
                }
            }
        });


        return array;
    }

    /** 创建采购订单后 - 剩余数据返回 */
    private JSONArray judgePurchaseNoReplenished(JSONArray purchaseRequireItems) {
        JSONArray returnData = new JSONArray();
        purchaseRequireItems.forEach(items -> {
            JSONObject itemObj = (JSONObject) items;
            double toBeReplenishedQty = itemObj.getDoubleValue("toBeReplenishedQty");
            double distributionQty = itemObj.getDoubleValue("distributionQty");
            double remainingQty = toBeReplenishedQty - distributionQty;
            if (remainingQty > 0) {
                itemObj.put("toBeReplenishedQty", remainingQty);
                itemObj.put("distributionQty", remainingQty);
                returnData.add(itemObj);
            }
        });
        return returnData;
    }

    // 判断商品导入是否为停用
    private void judgeProductState(JSONArray purchaseRequireItems) {
        Pattern p;
        Matcher m;
        String productIdStr = "";
        List errorProductIds = new ArrayList<>();
        for (int i = 0; i < purchaseRequireItems.size(); i++) {
            productIdStr += "'" + purchaseRequireItems.getJSONObject(i).getJSONObject("product").getString("id") + "',";
            double number = i / 1000;
            p = Pattern.compile("[1-9]*");
            m = p.matcher("" + number);
            if (m.matches() || i == purchaseRequireItems.size() - 1) {
                errorProductIds.addAll(productRepository.findAll("SELECT ID FROM MAS_PRODUCT WHERE ID IN (" + productIdStr.substring(0, productIdStr.length() - 1) + ") AND (STATE = '2' OR STATE = '3') "));
                productIdStr = "";
            }
        }
        if (errorProductIds.size() > 0) {
            throw new RuntimeException("停产下市、停用商品不可导入，请找替换产品采购！商品有" + errorProductIds.toString());
        }
    }

    // 分发三方询价要货并创建订单
    private JSONArray issueThirdInquireRequireOrder(JSONArray checkRequireItems) {
        JSONArray invaildData = new JSONArray();

        List<BusinessParam> businessParams = businessParamRepository.findAllByQueryKey("thirdSendPurOrder");
        businessParams.forEach(businessParam -> {
            List thirdRequireItems = this.filterThirdInquireItem(checkRequireItems, businessParam.getValue2());
            if (!thirdRequireItems.isEmpty()) {
                repleAcceptEntranceService.thirdCreatePurOrderRequestIssue(new JSONObject(MapUtil.mapper("purchaseRequireItems", thirdRequireItems)), businessParam.getValue2());
                invaildData.addAll(thirdRequireItems);
            }
        });

        return invaildData;
    }


    // 过滤三方询价要货明细
    private List filterThirdInquireItem(JSONArray requireItems, String method) {
        if ("supplierOrderService".equals(method)) {
            return requireItems.stream().filter(item -> {
                JSONObject param = (JSONObject) item;

                return Objects.nonNull(param.get("channelType")) && param.getIntValue("channelType") != 3;
            }).collect(Collectors.toList());

        } else if ("replePurOrderService".equals(method)) { // 装机
            return requireItems.stream().filter(item -> {
                JSONObject param = (JSONObject) item;

                boolean inquiryId = !StringUtils.isEmpty(param.get("commodityInquiryOrderId")) && !param.getString("commodityInquiryOrderId").startsWith("BT")
                        && !param.getString("commodityInquiryOrderId").startsWith("XJ") && !param.getString("commodityInquiryOrderId").startsWith("ST")
                        && Objects.isNull(param.get("channelType"));
                boolean channelTypeAndCommidInquIsNull = StringUtils.isEmpty(param.get("commodityInquiryOrderId")) && Objects.isNull(param.get("channelType"));
                return inquiryId || channelTypeAndCommidInquIsNull;
            }).collect(Collectors.toList());
        }
        return new ArrayList();
    }


    // 转储成功后判断是否还有数据生成
    private JSONObject notReplenishmentCompleted(JSONObject param) {
        JSONObject cloneParam = JSONObject.parseObject(param.toJSONString());
        SimpleRequest request = new SimpleRequest();

        // 重新获取明细
        JSONObject paramCondiAndItem = param.getJSONObject("queryCondiAndItem");
        paramCondiAndItem.remove("productRequireItems");
        request.setData(paramCondiAndItem);
        List<Map> dumpRequires;
        try {
            dumpRequires = this.queryRequireItem(request);
        } catch (Exception e) {
            if (e.getMessage().contains("未找到可补货数据!") || e.getMessage().contains("未找到要货相关数据")) {
                return new JSONObject(MapUtil.mapper("sumProductRequireItems", new JSONArray()));
            }
            throw new RuntimeException(e.getMessage());
        }

        // 循环拼接合适的数据返回
        JSONObject cloneQueryCondiAndItem = cloneParam.getJSONObject("queryCondiAndItem");
        cloneQueryCondiAndItem.remove("sumProductRequireItems");
        JSONArray oldProductRequireItems = cloneQueryCondiAndItem.getJSONArray("productRequireItems");
        if (oldProductRequireItems == null) return new JSONObject();
        this.filterMeetCondiRequireItem(oldProductRequireItems, dumpRequires);
        paramCondiAndItem.put("productRequireItems", dumpRequires);

        // 根据新的明细汇总，做转储准备
        request = new SimpleRequest();
        request.setData(paramCondiAndItem);
        JSONObject sumDumpRequireItem;

        // 二次循环异常不抛出，确保第一次数据发送成功
        try {
            sumDumpRequireItem = this.dumpSum(request);
        }catch (Exception e) {
            paramCondiAndItem.put("sumProductRequireItems", new JSONArray());
            return paramCondiAndItem;
        }
        sumDumpRequireItem.put("location", param.getJSONObject("location"));


        // 获取库存
        request = new SimpleRequest();
        request.setData(sumDumpRequireItem);
        JSONObject result = new JSONObject();
        try {
            result = this.obtainStock(request);
        } catch (Exception e) {
            result.put("sumProductRequireItems", new JSONArray());
            return result;
        }
        return result;
    }

    private void filterMeetCondiRequireItem(JSONArray oldRequireItems, List<Map> currentRequireItems) {
        oldRequireItems.forEach(oldRequireItem -> {
            JSONObject oldRequireItemObj = (JSONObject) oldRequireItem;
            String requireItemId = oldRequireItemObj.getString("id");
            String selectFlag = oldRequireItemObj.getString("selectFlag");
            String hideSelected = oldRequireItemObj.getString("hideSelected");
            String selected = oldRequireItemObj.getString("selected");

            currentRequireItems.forEach(currentRequireItem -> {
                JSONObject currentRequireItemObj = new JSONObject(currentRequireItem);
                if (requireItemId.equals(currentRequireItemObj.getString("id"))) {
                    currentRequireItemObj.put("selectFlag", selectFlag);
                    currentRequireItemObj.put("hideSelected", hideSelected);
                    currentRequireItemObj.put("selected", selected);
                }
            });
        });

    }



}
